package com.gbdata.zuul.wrapper;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.*;

/**
 * HttpServletResponse包装对象
 */
public class ContentCapturingResponseWrapper extends HttpServletResponseWrapper {
    private ByteArrayOutputStream buffer;
    private PrintWriter writer;

    public ContentCapturingResponseWrapper(HttpServletResponse response) throws IOException {
        super(response);
        buffer = new ByteArrayOutputStream();
        writer = new PrintWriter(new OutputStreamWriter(buffer, response.getCharacterEncoding()));
    }

    @Override
    public PrintWriter getWriter() {
        return writer;
    }

    @Override
    public void flushBuffer() throws IOException {
        if (writer != null) {
            writer.flush();
        }
        super.flushBuffer();
    }

    @Override
    public void reset() {
        buffer = new ByteArrayOutputStream();
        try {
            writer = new PrintWriter(new OutputStreamWriter(buffer, getResponse().getCharacterEncoding()));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public String getContent() throws IOException {
        flushBuffer();
        return buffer.toString();
    }

    public byte[] getContentAsByteArray() throws IOException {
        flushBuffer();
        return buffer.toByteArray();
    }


    public void copyToResponse(OutputStream outputStream) throws IOException {
        // 将包装器中的内容写入原始响应输出流
        outputStream.write(buffer.toByteArray());
    }
}
